<template>
  <div class="validation-rules">
    <el-table :data="validationRulesList" style="width: 100%" v-loading="loading">
      <el-table-column prop="ruleName" label="规则名称" width="150" />
      <el-table-column prop="ruleType" label="规则类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getRuleTypeTag(row.ruleType)">
            {{ getRuleTypeText(row.ruleType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="fieldName" label="字段名称" width="120" />
      <el-table-column prop="rulePattern" label="规则表达式" min-width="200" show-overflow-tooltip />
      <el-table-column prop="errorMessage" label="错误提示" min-width="150" show-overflow-tooltip />
      <el-table-column prop="priority" label="优先级" width="80" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            :type="row.status === 1 ? 'danger' : 'success'" 
            link 
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageInfo.pageNum"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑验证规则对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="ruleForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleType">
          <el-select v-model="ruleForm.ruleType" placeholder="请选择规则类型" style="width: 100%">
            <el-option label="正则表达式" value="REGEX" />
            <el-option label="长度验证" value="LENGTH" />
            <el-option label="范围验证" value="RANGE" />
            <el-option label="格式验证" value="FORMAT" />
            <el-option label="自定义" value="CUSTOM" />
          </el-select>
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="ruleForm.fieldName" placeholder="请输入字段名称" />
        </el-form-item>
        <el-form-item label="规则表达式" prop="rulePattern">
          <el-input 
            v-model="ruleForm.rulePattern" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入规则表达式，如：^1[3-9]\d{9}$"
          />
        </el-form-item>
        <el-form-item label="错误提示" prop="errorMessage">
          <el-input v-model="ruleForm.errorMessage" placeholder="请输入错误提示信息" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="ruleForm.priority" :min="1" :max="100" placeholder="请输入优先级" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="ruleForm.description" 
            type="textarea" 
            :rows="2" 
            placeholder="请输入规则描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getValidationRulesList, createValidationRule, updateValidationRule, deleteValidationRule, updateValidationRuleStatus } from '@/api/engine'

const loading = ref(false)
const validationRulesList = ref<any[]>([])
const total = ref(0)

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
})

const dialogVisible = ref(false)
const submitLoading = ref(false)
const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  id: undefined as number | undefined,
  ruleName: '',
  ruleType: 'REGEX',
  fieldName: '',
  rulePattern: '',
  errorMessage: '',
  priority: 1,
  status: 1,
  description: ''
})

const ruleRules: FormRules = {
  ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  fieldName: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
  rulePattern: [{ required: true, message: '请输入规则表达式', trigger: 'blur' }],
  errorMessage: [{ required: true, message: '请输入错误提示', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const dialogTitle = computed(() => 
  ruleForm.id ? '编辑验证规则' : '新增验证规则'
)

const getRuleTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'REGEX': 'primary',
    'LENGTH': 'success',
    'RANGE': 'warning',
    'FORMAT': 'info',
    'CUSTOM': 'danger'
  }
  return tagMap[type] || 'info'
}

const getRuleTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    'REGEX': '正则表达式',
    'LENGTH': '长度验证',
    'RANGE': '范围验证',
    'FORMAT': '格式验证',
    'CUSTOM': '自定义'
  }
  return textMap[type] || type
}

const fetchValidationRulesList = async () => {
  loading.value = true
  try {
    const response = await getValidationRulesList(pageInfo)
    validationRulesList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取验证规则列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  ruleForm.id = undefined
  ruleForm.ruleName = ''
  ruleForm.ruleType = 'REGEX'
  ruleForm.fieldName = ''
  ruleForm.rulePattern = ''
  ruleForm.errorMessage = ''
  ruleForm.priority = 1
  ruleForm.status = 1
  ruleForm.description = ''
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  ruleForm.id = row.id
  ruleForm.ruleName = row.ruleName
  ruleForm.ruleType = row.ruleType
  ruleForm.fieldName = row.fieldName
  ruleForm.rulePattern = row.rulePattern
  ruleForm.errorMessage = row.errorMessage
  ruleForm.priority = row.priority
  ruleForm.status = row.status
  ruleForm.description = row.description || ''
  dialogVisible.value = true
}

const handleToggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}规则"${row.ruleName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateValidationRuleStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    fetchValidationRulesList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则"${row.ruleName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteValidationRule(row.id)
    ElMessage.success('删除成功')
    fetchValidationRulesList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!ruleFormRef.value) return
  
  try {
    await ruleFormRef.value.validate()
    submitLoading.value = true
    
    if (ruleForm.id) {
      await updateValidationRule(ruleForm.id, ruleForm)
      ElMessage.success('更新成功')
    } else {
      await createValidationRule(ruleForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchValidationRulesList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  ruleFormRef.value?.resetFields()
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  fetchValidationRulesList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  fetchValidationRulesList()
}

onMounted(() => {
  fetchValidationRulesList()
})
</script>

<style scoped>
.validation-rules {
  padding: 20px;
}
</style>